﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace LdCms.Web.Controllers.API.Service.V1
{
    using LdCms.Common.Extension;
    using LdCms.Common.Net;
    using LdCms.Common.Utility;
    using LdCms.EF.DbModels;
    using LdCms.IBLL.Service;
    using LdCms.IBLL.Sys;
    using LdCms.Model.Service;
    using LdCms.Web.Services;
    /// <summary>
    /// 意见反馈接口：
    ///     01、保存留言
    ///        URL：service/message/board/save?uuid=uuid
    ///        POST：{"member_id":"sys","nick_name":"小草","name":"小草","company_name":"神马公司","phone":"13536444330","email":"asfd@163.com","image_src":"12312.jpg","address":"地址","content":"说明下"}
    ///     02、查询留言列表-分页
    ///        GET：service/message/board/list/paging?uuid=uuid&page=page=&count=count
    ///     03、查询留言详情
    ///        GET：service/message/board/get?uuid=uuid&id=id
    /// </summary>
    [ApiVersion("1.0")]
    [ControllerName("service/message/board")]
    public class ServiceMessageBoardController : BaseApiController
    {
        private readonly IBaseApiManager BaseApiManager;
        private readonly IConfigService ConfigService;
        private readonly IMessageBoardService MessageBoardService;
        public ServiceMessageBoardController(IBaseApiManager BaseApiManager, IConfigService ConfigService, IMessageBoardService MessageBoardService) : base(BaseApiManager)
        {
            this.BaseApiManager = BaseApiManager;
            this.ConfigService = ConfigService;
            this.MessageBoardService = MessageBoardService;
        }

        [HttpPost]
        [ActionName("save")]
        public IActionResult SaveMessageBoard(string uuid, [FromBody]ServiceMessageBoardSaveParams fromValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid, fromValue);
                string companyId = InterfaceAccount.CompanyID;
                bool isParams = IsSaveParams(fromValue);
                var entity = ToServiceMessageBoard(fromValue);
                var result = MessageBoardService.SaveMessageBoard(entity);
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        [HttpGet]
        [ActionName("list/paging")]
        public IActionResult GetMessageBoardPaging(string uuid)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid);
                string companyId = InterfaceAccount.CompanyID;
                int page = GetQueryString("page").ToInt();
                int count = GetQueryString("count").ToInt();
                string state = "true";
                int total = MessageBoardService.CountMessageBoard(SystemID, companyId, state);
                var lists = MessageBoardService.GetMessageBoardPaging(SystemID, companyId, state, page, count);
                if (lists == null) { return Error(logId, "not data！"); }
                var data = ToServiceMessageBoardResult(lists);
                return Success(logId, "ok", new { page, total, rows = data });
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpGet]
        [ActionName("get")]
        public IActionResult GetListPaging(string uuid)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid);
                string companyId = InterfaceAccount.CompanyID;
                string messageId = GetQueryString("id");
                var entity = MessageBoardService.GetMessageBoard(SystemID, companyId, messageId);
                if (entity == null)
                    return Error(logId, "not data！");
                var data = ToServiceMessageBoardResult(entity);
                return Success(logId, "ok", data);
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }

        #region 私有方法
        private bool IsKeyword(string[] keyword,string content)
        {
            foreach (var item in keyword)
            {
                if (content.ToLower().Contains(item.ToLower()))
                    return false;
            }
            return true;
        }
        private bool IsSaveParams(ServiceMessageBoardSaveParams fromValue)
        {
            try
            {
                if (fromValue == null)
                    throw new Exception("params not empty！");
                if (string.IsNullOrEmpty(fromValue.name))
                    throw new Exception("lack name params！");
                if (string.IsNullOrEmpty(fromValue.content))
                    throw new Exception("lack content params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private Ld_Service_MessageBoard ToServiceMessageBoard(ServiceMessageBoardSaveParams fromValue)
        {
            try
            {
                string companyId = InterfaceAccount.CompanyID;
                string ipAddress = Net.Ip;
                string memberId = fromValue.member_id.IIF();
                string name = fromValue.name.IIF();
                string nickName = fromValue.nick_name.IIF();
                string companyName = fromValue.company_name.IIF();
                string phone = fromValue.phone.IIF();
                string email = fromValue.email.IIF();
                string address = fromValue.address.IIF();
                string imgSrc = fromValue.image_src.IIF();
                string content = fromValue.content.IIF();

                if (!Utility.IsMobilePhone(phone))
                    throw new Exception("手机号码格式不正确！");
                if (!Utility.IsEmail(email))
                    throw new Exception("邮箱地址格式不正确！");

                var entityConfig = ConfigService.GetConfig(SystemID, companyId);
                if (entityConfig != null)
                {
                    string Shielding = entityConfig.Shielding;
                    if (!string.IsNullOrWhiteSpace(Shielding))
                    {
                        string[] keyword = Shielding.Split("|");
                        if (!IsKeyword(keyword, content))
                            throw new Exception("内容有非法虑字！");
                    }
                }
                var entity = new Ld_Service_MessageBoard()
                {
                    SystemID = SystemID,
                    CompanyID = companyId,
                    MemberID = memberId,
                    NickName = nickName,
                    CompanyName = companyName,
                    Name = name,
                    Tel = phone,
                    Phone = phone,
                    Email = email,
                    Address = address,
                    ImgSrc = imgSrc,
                    Content = content,
                    IpAddress = ipAddress
                };
                return entity;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private object ToServiceMessageBoardResult(Ld_Service_MessageBoard entity)
        {
            try
            {
                var data = new
                {
                    id = entity.MessageID,
                    company_name = entity.CompanyName.IIF(),
                    name = entity.Name.IIF(),
                    phone = entity.Phone.IIF(),
                    email = entity.Email.IIF(),
                    address = entity.Address.IIF(),
                    image_src = entity.ImgSrc.IIF(),
                    content = entity.Content.IIF(),
                    reply = entity.Reply.IIF(),
                    staff_id = entity.ReplyStaffId.IIF(),
                    staff_name = entity.ReplyStaffName.IIF(),
                    reply_time = entity.ReplyTime.HasValue? entity.ReplyTime.ToDate().ToString("yyyy-MM-dd HH:mm:ss"):"",
                    ip = entity.IpAddress.IIF(),
                    date = entity.CreateDate
                };
                return data;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private object ToServiceMessageBoardResult(List<Ld_Service_MessageBoard> lists)
        {
            try
            {
                var data = from m in lists
                           select new
                           {
                               id = m.MessageID,
                               company_name = m.CompanyName.IIF(),
                               name = m.Name.IIF(),
                               phone = m.Phone.IIF(),
                               email = m.Email.IIF(),
                               address = m.Address.IIF(),
                               image_src = m.ImgSrc.IIF(),
                               content = m.Content.IIF(),
                               reply = m.Reply.IIF(),
                               staff_id = m.ReplyStaffId.IIF(),
                               staff_name = m.ReplyStaffName.IIF(),
                               reply_time = m.ReplyTime.HasValue ? m.ReplyTime.ToDate().ToString("yyyy-MM-dd HH:mm:ss") : "",
                               ip = m.IpAddress.IIF(),
                               date = m.CreateDate
                           };
                return data;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

    }
}